//
//  ChatMessageFrame.m
//  YSTChatUIKit
//
//  Created by 王文文 on 2018/2/13.
//  Copyright © 2018年 王文文. All rights reserved.
//

#import "ChatMessageFrame.h"
#import "LiuqsDecoder.h"


@implementation ChatMessageFrame

- (void)setMessage:(ChatMessage *)message {
    
    _message = message;
    
    CGFloat headW  = 40;
    CGFloat headH  = 40;
    CGFloat margin = 10;
    
    //1,计算头像的位置
    CGFloat headX = message.userType ? SCREEN_WITDTH - headW - margin : margin;
    self.headViewFrame = CGRectMake(headX, margin, headW, headH);
    
    //2，计算昵称的位置
    CGRect nameFrame = CGRectMake(CGRectGetMaxX(self.headViewFrame) + margin, CGRectGetMinY(self.headViewFrame), SCREEN_WITDTH - margin * 2 - headW, 20);
    self.nameLabelFrame = message.userType == userTypeMe ? nameFrame : CGRectZero;
    
//    // 3、计算内容位置
    CGFloat contentX = CGRectGetMaxX(self.headViewFrame)+margin;
   
    
     CGSize contentSize;
    if (message.messageType == messageTypeText) {
        NSMutableAttributedString *attMessage = [LiuqsDecoder decodeWithPlainStr:message.messageContent font:[UIFont systemFontOfSize:17.0f]];
        
        self.attMessage = attMessage;
        
        CGFloat AllMargin = 31;
        
        CGSize maxsize = CGSizeMake(SCREEN_WITDTH - (margin * 4 + headW * 2) - AllMargin, MAXFLOAT);
        
        // 创建文本容器
        YYTextContainer *container = [YYTextContainer new];
        container.size = maxsize;
        container.maximumNumberOfRows = 0;
        // 生成排版结果
        YYTextLayout *layout = [YYTextLayout layoutWithContainer:container text:self.attMessage];
        
        CGFloat textW = layout.textBoundingSize.width > maxsize.width ? maxsize.width : layout.textBoundingSize.width;
        
        
        CGFloat airX = message.userType ? SCREEN_WITDTH - margin * 2 - headW - textW - AllMargin : margin * 2 + headW;
        
        self.airViewFrame = CGRectMake(airX, 35, textW + 31, layout.textBoundingSize.height + 16);
        
         contentX = message.userType ? SCREEN_WITDTH - margin * 2 - headW - textW - 18 : margin * 2 + headW + 20;
        
        self.messageLabelFrame = CGRectMake(contentX, 43, textW, layout.textBoundingSize.height);
        
        self.cellHeight = CGRectGetMaxY(self.messageLabelFrame) + margin * 2;
    }
    
    if (message.messageType == messageTypePicture) {
        contentSize = CGSizeMake(150, 150);
        self.messageLabelFrame = CGRectMake(contentX, 43, contentSize.width + 25, contentSize.height + 30);
        self.cellHeight = CGRectGetMaxY(self.messageLabelFrame) + margin * 2;
        
    }
    
    
    
}

@end
